package com.hyx.api.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hyx.api.domain.*;
import com.hyx.api.domain.bo.*;
import com.hyx.api.domain.vo.*;
import com.hyx.api.enums.*;
import com.hyx.api.mapper.*;
import com.hyx.api.service.IAppRecoverService;
import com.hyx.api.utils.GenSerialNoUtil;
import com.hyx.api.utils.base.MobileBaseService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class IAppRecoverServiceImpl implements IAppRecoverService {

    private static final Logger log = LoggerFactory.getLogger(IAppRecoverServiceImpl.class);

    @Autowired
    private InquiryOrderMapper inquiryOrderMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private VerifyModelOptionMapper verifyModelOptionMapper;
    @Autowired
    private FileUploadMapper uploadMapper;
    @Autowired
    private OfferOrderMapper offerOrderMapper;
    @Autowired
    private MobileBaseService mobileBaseService;
    @Autowired
    private RecycleBusinessMapper recycleBusMapper;
    @Autowired
    private RecycleOrderMapper recycleOrderMapper;
    @Autowired
    private RefundOrderMapper refundOrderMapper;
    @Autowired
    private SpreadOrderMapper spreadOrderMapper;
    @Autowired
    private ModelMapper modelMapper;
    @Autowired
    private MsgDialogueOrderMapper msgDialogueMapper;
    @Autowired
    private PriceDownFormulaMapper priceDownFormulaMapper;
    @Autowired
    private RecycleReceivingAddrMapper receivingAddrMapper;
    @Autowired
    private CfgAreaMapper areaMapper;
    @Autowired
    private CompanyRecoverInfoMapper companyRecoverInfoMapper;
    @Autowired
    private CustomerWithdrawMapper withdrawMapper;
    @Autowired
    private WalletMapper walletMapper;

    @Override
    public List<RecoverInquiryOrderListVo> queryInquiryOrderList(Integer offerStatus) {
        User currentUser = mobileBaseService.hasLogin();
        List<RecoverInquiryOrderListVo> resList = new ArrayList<>();
        List<InquiryOrderVo> inquiryOrders;
        if (offerStatus != 3) {
            //与数据库对应
            if (offerStatus == 0) offerStatus = 3;
            if (UserTypeEnum.OFFER_OPERATOR.code().equals(currentUser.getType())) {
                inquiryOrders = inquiryOrderMapper.queryListForOfferStatus(offerStatus, currentUser.getId(), null);
            } else if (UserTypeEnum.SUM_ACCOUNT.code().equals(currentUser.getType())) {
                inquiryOrders = inquiryOrderMapper.queryListForOfferStatus(offerStatus, null, currentUser.getRecoveryId());
            } else {
                return new ArrayList<>();
            }
        } else {
            QueryWrapper<RecycleOrder> recycleWrapper = new QueryWrapper<>();
            recycleWrapper.eq("status", RecycleOrderStatusEnum.NO_PAY.code());
            if (UserTypeEnum.OFFER_OPERATOR.code().equals(currentUser.getType())) {
                recycleWrapper.eq("recycle_operator_id", currentUser.getId());
            } else if (UserTypeEnum.SUM_ACCOUNT.code().equals(currentUser.getType())) {
                recycleWrapper.eq("recycle_bus_id", currentUser.getRecoveryId());
            } else {
                return new ArrayList<>();
            }
            List<RecycleOrder> recycleOrders = recycleOrderMapper.selectList(recycleWrapper);
            if (recycleOrders.isEmpty()) {
                return new ArrayList<>();
            }
            List<Long> inquiryIds = recycleOrders.stream().map(RecycleOrder::getInquiryOrderId).collect(Collectors.toList());
            inquiryOrders = inquiryOrderMapper.queryOrderBatchIds(inquiryIds);
        }
        for (InquiryOrderVo inquiryOrder : inquiryOrders) {
            RecoverInquiryOrderListVo res = new RecoverInquiryOrderListVo();
            User user = userMapper.selectById(inquiryOrder.getUserId());
            Company company = companyMapper.selectById(user.getCompanyId());
            Company shop = companyMapper.selectById(user.getStoreId());
            res.setCompanyName(company.getName());
            res.setShopName(shop.getName());
            res.setCreateTime(inquiryOrder.getCreateTime());
            res.setModelName(inquiryOrder.getModelName());
            List<VerifyModelOption> modelOptions = verifyModelOptionMapper.selectBatchIds(Arrays.asList(inquiryOrder.getVerifyModelIds().split(",")));
            String specs = modelOptions.stream().filter(s -> s.getType() == 1).map(VerifyModelOption::getName).collect(Collectors.joining(","));
            res.setSpecs(specs);
            res.setId(inquiryOrder.getId());
            List<FileUpload> files = uploadMapper.selectBatchIds(Arrays.asList(inquiryOrder.getFileIds().split(",")));
            List<String> fileUrls = files.stream().map(FileUpload::getUrl).collect(Collectors.toList());
            res.setFileUrls(fileUrls);
            LambdaQueryWrapper<MsgDialogueOrder> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(MsgDialogueOrder::getInquiryOrderId, inquiryOrder.getId());
            wrapper.eq(MsgDialogueOrder::getIsRead, YesNoEnum.NO.code());
            wrapper.eq(MsgDialogueOrder::getReceiveUser, currentUser.getId());
            res.setMsgNoReadCount(msgDialogueMapper.selectCount(wrapper));
            resList.add(res);
        }
        return resList;
    }

    @Override
    public AjaxResult queryIsAllowOffer(Integer inquiryOrderId) {
        QueryWrapper<OfferOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("inquiry_order_id", inquiryOrderId);
        wrapper.eq("status", OfferStatusEnum.OFFERING.code());
        OfferOrder offerOrder = offerOrderMapper.selectOne(wrapper);
        if (offerOrder != null) {
            User user = userMapper.selectById(offerOrder.getOfferOperatorId());
            return AjaxResult.error("'" + user.getNickName() + "'，正在报价，请稍后");
        }
        InquiryOrder inquiryOrder = inquiryOrderMapper.selectById(inquiryOrderId);
        if (new Date().before(DateUtil.offsetMinute(inquiryOrder.getCreateTime(), 10))) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("已超过报价时限，报价失败");
        }
    }

    @Override
    public AjaxResult queryOfferOrderByInquiryId(Integer inquiryOrderId) {
        InquiryOrderDetailVo res = new InquiryOrderDetailVo();
        InquiryOrder inquiryOrder = inquiryOrderMapper.selectById(inquiryOrderId);
        res.setId(inquiryOrder.getId());
        List<FileUpload> files = uploadMapper.selectBatchIds(Arrays.asList(inquiryOrder.getFileIds().split(",")));
        List<String> fileUrls = files.stream().map(FileUpload::getUrl).collect(Collectors.toList());
        res.setFileUrls(fileUrls);
        res.setRemark(inquiryOrder.getRemark());
        res.setModelName(inquiryOrder.getModelName());
        List<VerifyModelOption> modelOptions = verifyModelOptionMapper.selectBatchIds(Arrays.asList(inquiryOrder.getVerifyModelIds().split(",")));
        String specs = modelOptions.stream().filter(s -> s.getType() == 1).map(VerifyModelOption::getName).collect(Collectors.joining(","));
        res.setSpecs(specs);
        res.setIemi(inquiryOrder.getIemi());
        res.setCreateTime(inquiryOrder.getCreateTime());
        QueryWrapper<OfferOrder> offerWrapper = new QueryWrapper<>();
        offerWrapper.eq("inquiry_order_id", inquiryOrderId);
        offerWrapper.eq("status", OfferStatusEnum.OFFER_FINISH.code());
        offerWrapper.orderByDesc("offer_price");
        List<OfferOrder> offerOrders = offerOrderMapper.selectList(offerWrapper);
        List<OfferOrderVo> offerOrderVoList = new ArrayList<>();
        if (offerOrders.size() > 0) {
            //只取当前报价最高的
            OfferOrder order = offerOrders.get(0);
            User user = userMapper.selectById(order.getOfferOperatorId());
            OfferOrderVo offerOrderVo = new OfferOrderVo();
            BeanUtils.copyProperties(order, offerOrderVo);
            RecycleBusiness recycleBus = recycleBusMapper.selectById(user.getRecoveryId());
            offerOrderVo.setOfferBusName(recycleBus.getName());
            offerOrderVo.setOfferOperatorName(user.getNickName());
            offerOrderVoList.add(offerOrderVo);
        }
        res.setOfferOrderList(offerOrderVoList);
        res.setVerifyOptionIds(modelOptions.stream().map(VerifyModelOption::getId).collect(Collectors.toList()));
        return AjaxResult.success(res);
    }

    @Override
    public AjaxResult addOfferOrder(OfferOrderBo bo) {
        //获取当前用户信息
        User user = mobileBaseService.hasLogin();
        InquiryOrder inquiryOrder = inquiryOrderMapper.selectById(bo.getInquiryOrderId());
        if (new Date().after(DateUtil.offsetMinute(inquiryOrder.getCreateTime(), 10))) {
            return AjaxResult.error("已超过报价时限，报价失败");
        }
        LambdaQueryWrapper<OfferOrder> lqw = Wrappers.lambdaQuery();
        lqw.eq(OfferOrder::getInquiryOrderId, bo.getInquiryOrderId());
        lqw.eq(OfferOrder::getOfferOperatorId, user.getId());
        OfferOrder order = offerOrderMapper.selectOne(lqw);
        if (ObjectUtils.isNotEmpty(order)) {
            return AjaxResult.success(order);
        }

        //新增
        OfferOrder offerOrderDO = new OfferOrder();
        offerOrderDO.setInquiryOrderId(bo.getInquiryOrderId());
        offerOrderDO.setOfferBusId(user.getRecoveryId());
        offerOrderDO.setOfferOperatorId(user.getId());
        offerOrderDO.setStartTime(new Date());
        offerOrderDO.setStatus(OfferStatusEnum.OFFERING.code());
        offerOrderDO.setIsSuccessful(0);
        offerOrderMapper.insert(offerOrderDO);
        return AjaxResult.success(offerOrderDO);
    }

    @Override
    public AjaxResult updateOfferOrder(OfferOrderBo bo) {
        OfferOrder tempDO = offerOrderMapper.selectById(bo.getId());
        if (tempDO == null) {
            return AjaxResult.error("没有该记录，不能更改");
        }
        OfferOrder offerOrder = new OfferOrder();
        offerOrder.setId(bo.getId());
        offerOrder.setStatus(bo.getStatus());
        offerOrder.setOfferPrice(bo.getOfferPrice());
        offerOrder.setEndTime(new Date());
        //存在金额报价完成
        if (ObjectUtils.isNotEmpty(bo.getOfferPrice())) {
            offerOrder.setStatus(2);
            //校验钱包余额是否足够支持报价，且是否高于5000
            LambdaQueryWrapper<Wallet> walletWrapper = Wrappers.lambdaQuery();
            walletWrapper.eq(Wallet::getRecoveryBusId, tempDO.getOfferBusId());
            Wallet recoveryWallet = walletMapper.selectOne(walletWrapper);
            if (recoveryWallet.getMoney().compareTo(new BigDecimal(5000)) < 0) {
                return AjaxResult.error("余额低于5000，禁止报价");
            } else if (recoveryWallet.getMoney().compareTo(bo.getOfferPrice()) < 0) {
                return AjaxResult.error("余额不足，报价失败!");
            }
        }

        InquiryOrder inquiryOrder = inquiryOrderMapper.selectById(tempDO.getInquiryOrderId());
        if (new Date().after(DateUtil.offsetMinute(inquiryOrder.getCreateTime(), 10))) {
            return AjaxResult.error("已超过报价时限，报价失败");
        }
        User user = userMapper.selectById(inquiryOrder.getUserId());
        Company company = companyMapper.selectById(user.getCompanyId());

        if (Objects.equals(company.getRateOpen(), YesNoEnum.YES.code())) {
            LambdaQueryWrapper<PriceDownFormula> lqw = Wrappers.lambdaQuery();
            lqw.eq(PriceDownFormula::getCompanyId, user.getCompanyId());
            lqw.le(PriceDownFormula::getBeginAmount, bo.getOfferPrice());
            lqw.ge(PriceDownFormula::getEndAmount, bo.getOfferPrice());
            lqw.orderByDesc(PriceDownFormula::getId);
            lqw.last("limit 1");
            List<PriceDownFormula> formulas = priceDownFormulaMapper.selectList(lqw);
            if (ObjectUtils.isNotEmpty(formulas)) {
                PriceDownFormula formula = formulas.get(0);
                offerOrder.setCompanyRateId(formula.getId());
                BigDecimal rate = new BigDecimal(formula.getRate()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
                BigDecimal handledAmount = offerOrder.getOfferPrice().multiply(rate); //利率金额
                if (ObjectUtils.isNotEmpty(formula.getUpperLimitAmount())) {
                    if (formula.getUpperLimitAmount().compareTo(handledAmount) < 0) {
                        handledAmount = formula.getUpperLimitAmount();
                    }
                }
                offerOrder.setRateAmount(offerOrder.getOfferPrice().subtract(handledAmount));
            }
        }

        offerOrderMapper.updateById(offerOrder);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult recycleOrderConfirmReceiving(RecOrderStaUpdateBo bo) {
        RecycleOrder recycleOrder = recycleOrderMapper.selectById(bo.getId());
        if (recycleOrder == null) {
            return AjaxResult.error("没有该回收订单，请核实");
        }
        if (!recycleOrder.getStatus().equals(RecycleOrderStatusEnum.NO_RECEIVING.code())) {
            return AjaxResult.error("该订单还未发货或者已取消，不能确认收货");
        }
        recycleOrder.setStatus(RecycleOrderStatusEnum.FINISH.code());
        recycleOrder.setReceivingTime(bo.getReceivingTime() == null ? new Date() : bo.getReceivingTime());
        recycleOrder.setRemark(bo.getRemark());
        recycleOrderMapper.updateById(recycleOrder);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult refundOrderCreate(Long recycleOrderId) {
        RecycleOrder recycleOrder = recycleOrderMapper.selectById(recycleOrderId);
        if (recycleOrder == null) {
            return AjaxResult.error("该回收订单不存在，无法退货");
        }
        QueryWrapper<RefundOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("recycle_order_id", recycleOrderId);
        Long count = refundOrderMapper.selectCount(wrapper);
        if (count == 0) {
            RefundOrder refundOrder = new RefundOrder();
            refundOrder.setRecycleOrderId(recycleOrderId);
            refundOrder.setRefundNo(GenSerialNoUtil.genOrderSn(SnTypeEnum.REFUND));
            refundOrder.setStatus(RefundStatusEnum.AUDITING.code());
            refundOrderMapper.insert(refundOrder);
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult addSpreadOrder(SpreadOrderBo bo) {
        User user = mobileBaseService.hasLogin();
        if (bo.getRecycleOrderId() == null) {
            return AjaxResult.error("没有该回收订单，请核实");
        }
        bo.setOperatorId(user.getId());
        SpreadOrder spreadDO = new SpreadOrder();
        BeanUtils.copyProperties(bo, spreadDO);
        spreadOrderMapper.insert(spreadDO);
        return AjaxResult.success("生成追差订单成功");
    }

    @Override
    public AjaxResult updateSpreadOrder(SpreadOrderBo bo) {
        User user = mobileBaseService.hasLogin();
        if (bo.getId() == null) {
            return AjaxResult.error("参数错误，无法修改");
        }
        SpreadOrder spreadOrder = spreadOrderMapper.selectById(bo.getId());
        if (spreadOrder == null) {
            return AjaxResult.error("没有该追差订单，无法修改");
        }
        if (bo.getSpread() != null) {
            spreadOrder.setSpread(bo.getSpread());
        }
        if (bo.getStatus() != null) {
            spreadOrder.setStatus(bo.getStatus());
        }
        if (bo.getPayImg() != null) {
            spreadOrder.setPayImg(bo.getPayImg());
        }
        spreadOrder.setOperatorId(user.getId());
        spreadOrderMapper.updateById(spreadOrder);
        return AjaxResult.success("修改成功");
    }

    @Override
    public AjaxResult queryInquiryOrderDetail(Long inquiryOrderId) {
        InquiryOrderDetailVo resDO = new InquiryOrderDetailVo();
        InquiryOrder inquiryOrder = inquiryOrderMapper.selectById(inquiryOrderId);
        resDO.setId(inquiryOrderId);
        resDO.setCreateTime(inquiryOrder.getCreateTime());
        resDO.setIemi(inquiryOrder.getIemi());
        resDO.setModelName(inquiryOrder.getModelName());
        resDO.setRemark(inquiryOrder.getRemark());
        List<FileUpload> files = uploadMapper.selectBatchIds(Arrays.asList(inquiryOrder.getFileIds().split(",")));
        List<String> fileUrls = files.stream().map(FileUpload::getUrl).collect(Collectors.toList());
        resDO.setFileUrls(fileUrls);
        List<VerifyModelOption> modelOptions = verifyModelOptionMapper.selectBatchIds(Arrays.asList(inquiryOrder.getVerifyModelIds().split(",")));
        String specs = modelOptions.stream().filter(s -> s.getType() == 1).map(VerifyModelOption::getName).collect(Collectors.joining(","));
        resDO.setSpecs(specs);
        resDO.setModelVo(modelMapper.selectVoById(inquiryOrder.getModelId()));
        LambdaQueryWrapper<OfferOrder> offerWrapper = Wrappers.lambdaQuery();
        offerWrapper.eq(OfferOrder::getInquiryOrderId, inquiryOrderId);
        resDO.setOfferOrderList(offerOrderMapper.selectVoList(offerWrapper));
        LambdaQueryWrapper<RecycleOrder> recycleWrapper = Wrappers.lambdaQuery();
        recycleWrapper.eq(RecycleOrder::getInquiryOrderId, inquiryOrderId);
        List<RecycleOrder> recycleOrderVos = recycleOrderMapper.selectList(recycleWrapper);
        if (!recycleOrderVos.isEmpty()) {
            RecycleOrder recycleOrder = recycleOrderVos.get(0);
            RecycleOrderVo recycleOrderVo = new RecycleOrderVo();
            BeanUtils.copyProperties(recycleOrder, recycleOrderVo);
            LambdaQueryWrapper<RefundOrder> refundWrapper = Wrappers.lambdaQuery();
            refundWrapper.eq(RefundOrder::getRecycleOrderId, recycleOrder.getId());
            refundWrapper.orderByDesc(RefundOrder::getId);
            recycleOrderVo.setRefundOrderVo(refundOrderMapper.selectVoList(refundWrapper));
            LambdaQueryWrapper<SpreadOrder> spreadWrapper = Wrappers.lambdaQuery();
            spreadWrapper.eq(SpreadOrder::getRecycleOrderId, recycleOrder.getId());
            recycleOrderVo.setSpreadOrderVo(spreadOrderMapper.selectVoList(spreadWrapper));
            LambdaQueryWrapper<CustomerWithdraw> withdrawWrapper = Wrappers.lambdaQuery();
            withdrawWrapper.eq(CustomerWithdraw::getRecycleOrderId, recycleOrder.getId());
            CustomerWithdraw withdraw = withdrawMapper.selectOne(withdrawWrapper);
            if (withdraw != null) {
                recycleOrderVo.setCustomerWithdraw(withdraw);
            }
            RecycleReceivingAddr receivingAddr = receivingAddrMapper.selectById(recycleOrder.getReceivingAddrId());
            if (receivingAddr != null) {
                recycleOrderVo.setReceivingAddr(receivingAddr.getFullAddr());
                recycleOrderVo.setReceivingName(receivingAddr.getContactName());
                recycleOrderVo.setReceivingMobile(receivingAddr.getContactMobile());
            }
            resDO.setRecycleOrderVo(recycleOrderVo);
        }
        return AjaxResult.success(resDO);
    }

    @Override
    public AjaxResult queryRecoverWorkCount(String queTime) {
        RecoverWorkCountVo resDO = new RecoverWorkCountVo();

        User currentUser = mobileBaseService.hasLogin();
        if (UserTypeEnum.OFFER_OPERATOR.code().equals(currentUser.getType())) {
            //未报价数量
            Long waitOfferCount = inquiryOrderMapper.queryCountForOfferStatus(3, currentUser.getId(), null);
            resDO.setWaitOfferCount(waitOfferCount);
            //报价中数量
            Long alreadyOfferCount = inquiryOrderMapper.queryCountForOfferStatus(1, currentUser.getId(), null);
            resDO.setAlreadyOfferCount(alreadyOfferCount);
        } else if (UserTypeEnum.SUM_ACCOUNT.code().equals(currentUser.getType())) {
            //未报价数量
            Long waitOfferCount = inquiryOrderMapper.queryCountForOfferStatus(3, null, currentUser.getRecoveryId());
            resDO.setWaitOfferCount(waitOfferCount);
            //报价中数量
            Long alreadyOfferCount = inquiryOrderMapper.queryCountForOfferStatus(1, null, currentUser.getRecoveryId());
            resDO.setAlreadyOfferCount(alreadyOfferCount);
        } else {
            log.error("登录用户为非门店用户,当前登录用户为:{}", currentUser.getUsername());
            return AjaxResult.error("没有权限");
        }
        QueryWrapper<RecycleOrder> recycleWrapper = new QueryWrapper<>();
        recycleWrapper.eq("status", RecycleOrderStatusEnum.NO_PAY.code());
        if (UserTypeEnum.OFFER_OPERATOR.code().equals(currentUser.getType())) {
            recycleWrapper.eq("recycle_operator_id", currentUser.getId());
        } else if (UserTypeEnum.SUM_ACCOUNT.code().equals(currentUser.getType())) {
            recycleWrapper.eq("recycle_bus_id", currentUser.getRecoveryId());
        }
        Long waitPayCount = recycleOrderMapper.selectCount(recycleWrapper);
        resDO.setWaitPayCount(waitPayCount);

        Date initDate = new Date();
        if (StringUtils.isNotEmpty(queTime)) {
            initDate = DateUtil.parse(queTime, "yyyy-MM-dd");
        }
        DateTime beginDate = DateUtil.beginOfDay(initDate);
        DateTime endDate = DateUtil.endOfDay(initDate);

        LambdaQueryWrapper<OfferOrder> offerWrapper = Wrappers.lambdaQuery();
        offerWrapper.between(OfferOrder::getEndTime, beginDate, endDate);
        offerWrapper.eq(OfferOrder::getOfferOperatorId, currentUser.getId());
        resDO.setOfferCount(offerOrderMapper.selectCount(offerWrapper));

        LambdaQueryWrapper<RecycleOrder> successCountWrapper = Wrappers.lambdaQuery();
        successCountWrapper.between(RecycleOrder::getReceivingTime, beginDate, endDate);
        successCountWrapper.eq(RecycleOrder::getRecycleOperatorId, currentUser.getId());
        ArrayList<Integer> recycleStaList = new ArrayList<>();
        recycleStaList.add(RecycleOrderStatusEnum.NO_SEND.code());
        recycleStaList.add(RecycleOrderStatusEnum.NO_RECEIVING.code());
        recycleStaList.add(RecycleOrderStatusEnum.FINISH.code());
        successCountWrapper.in(RecycleOrder::getStatus, recycleStaList);
        resDO.setSuccessCount(recycleOrderMapper.selectCount(successCountWrapper));
        return AjaxResult.success(resDO);
    }

    @Override
    public AjaxResult queryRecycleStaticsInfo(RecycleStaticsQueBo bo) {
        User user = mobileBaseService.hasLogin();
        RecoverStaticsVo resDO = new RecoverStaticsVo();
        Date queTime = bo.getQueTime();
        if (queTime == null) {
            queTime = new Date();
        }
        Date oldTime = DateUtil.offsetDay(queTime, -1);
        BigDecimal turnoverAmount, lastTurnoverAmount;
        if (user.getType().equals(UserTypeEnum.OFFER_OPERATOR.code())) {
            turnoverAmount = recycleOrderMapper.queryRecycleSuccessAmountByTimeUser(queTime, 1,
                    user.getId(), null);
            lastTurnoverAmount = recycleOrderMapper.queryRecycleSuccessAmountByTimeUser(oldTime, 1,
                    user.getId(), null);
        } else if (user.getType().equals(UserTypeEnum.SUM_ACCOUNT.code())) {
            turnoverAmount = recycleOrderMapper.queryRecycleSuccessAmountByTimeUser(queTime, 1,
                    null, user.getRecoveryId());
            lastTurnoverAmount = recycleOrderMapper.queryRecycleSuccessAmountByTimeUser(oldTime, 1,
                    null, user.getRecoveryId());
        } else {
            return AjaxResult.error("没有权限");
        }
        if (lastTurnoverAmount == null) lastTurnoverAmount = BigDecimal.ZERO;
        resDO.setTurnoverAmount(turnoverAmount == null ? BigDecimal.ZERO : turnoverAmount);
        resDO.setTurnoverAmountYesterday(lastTurnoverAmount);
        if (resDO.getTurnoverAmount().compareTo(lastTurnoverAmount) > 0) {
            if (lastTurnoverAmount.compareTo(BigDecimal.ZERO) == 0) {
                resDO.setTurnoverAmountThanOldTimeUp(resDO.getTurnoverAmount().doubleValue());
            } else {
                resDO.setTurnoverAmountThanOldTimeUp(resDO.getTurnoverAmount().subtract(lastTurnoverAmount)
                        .divide(lastTurnoverAmount, 2, BigDecimal.ROUND_HALF_UP).doubleValue());
            }
        } else if (resDO.getTurnoverAmount().compareTo(lastTurnoverAmount) < 0) {
            if (resDO.getTurnoverAmount().compareTo(BigDecimal.ZERO) == 0) {
                resDO.setTurnoverAmountThanOldTimeDown(lastTurnoverAmount.doubleValue());
            } else {
                resDO.setTurnoverAmountThanOldTimeDown(lastTurnoverAmount.subtract(resDO.getTurnoverAmount())
                        .divide(lastTurnoverAmount, 2, BigDecimal.ROUND_HALF_UP).doubleValue());
            }
        }

        resDO.setInquiryCount(inquiryOrderMapper.queryRecycleInquiryCountByTimeBus(queTime));

        if (user.getType().equals(UserTypeEnum.OFFER_OPERATOR.code())) {
            resDO.setOfferCount(offerOrderMapper.queryOfferCountByTimeUser(queTime, 1, user.getId(), null,
                    null));
            resDO.setSuccessCount(recycleOrderMapper.queryRecycleSuccessCountByTimeUser(queTime, 1, user.getId(),
                    null));
            resDO.setOfferFailCount(offerOrderMapper.queryOfferCountByTimeUser(queTime, 1, user.getId(), null,
                    false));
            resDO.setRefundCount(refundOrderMapper.queryRefundCountByTimeUser(queTime, user.getId(), null));
            BigDecimal recycleAveragePrice = recycleOrderMapper.queryRecycleAvgAmountForTime(queTime, user.getId(),
                    null);
            resDO.setRecycleAveragePrice(recycleAveragePrice == null ? BigDecimal.ZERO : recycleAveragePrice);
        } else if (user.getType().equals(UserTypeEnum.SUM_ACCOUNT.code())) {
            resDO.setOfferCount(offerOrderMapper.queryOfferCountByTimeUser(queTime, 1, null, user.getRecoveryId(),
                    null));
            resDO.setSuccessCount(recycleOrderMapper.queryRecycleSuccessCountByTimeUser(queTime, 1, null,
                    user.getRecoveryId()));
            resDO.setOfferFailCount(offerOrderMapper.queryOfferCountByTimeUser(queTime, 1, null, user.getRecoveryId(),
                    false));
            resDO.setRefundCount(refundOrderMapper.queryRefundCountByTimeUser(queTime, null, user.getRecoveryId()));
            BigDecimal recycleAveragePrice = recycleOrderMapper.queryRecycleAvgAmountForTime(queTime, null,
                    user.getRecoveryId());
            resDO.setRecycleAveragePrice(recycleAveragePrice == null ? BigDecimal.ZERO : recycleAveragePrice);
        }

        double offerRate;
        if (resDO.getInquiryCount() == 0) {
            offerRate = 0D;
        } else {
            offerRate = BigDecimal.valueOf((float) resDO.getOfferCount() / resDO.getInquiryCount().doubleValue()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
        resDO.setOfferRate(offerRate);

        double successRate;
        if (resDO.getOfferCount() == 0) {
            successRate = 0D;
        } else {
            successRate = BigDecimal.valueOf((float) resDO.getSuccessCount() / resDO.getOfferCount().doubleValue()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
        resDO.setSuccessRate(successRate);

        DateTime startTime = DateUtil.offsetDay(queTime, -6);
        List<KeyValueVo> tendencyList = getRecycleTendencyForInquiryCount(startTime, user, bo.getRecycleTendencyType());
        KeyValueVo kvVo = new KeyValueVo();
        kvVo.setKey(DateUtil.today().split("-")[2] + "日");
        if (RecycleTendencyEnum.INQUIRY_COUNT.code().equals(bo.getRecycleTendencyType())) {
            kvVo.setValue(resDO.getInquiryCount());
        } else if (RecycleTendencyEnum.OFFER_COUNT.code().equals(bo.getRecycleTendencyType())) {
            kvVo.setValue(resDO.getOfferCount());
        } else if (RecycleTendencyEnum.SUCCESS_COUNT.code().equals(bo.getRecycleTendencyType())) {
            kvVo.setValue(resDO.getSuccessCount());
        } else if (RecycleTendencyEnum.SUCCESS_RATE.code().equals(bo.getRecycleTendencyType())) {
            kvVo.setValue(resDO.getSuccessRate());
        } else if (RecycleTendencyEnum.SUCCESS_AMOUNT.code().equals(bo.getRecycleTendencyType())) {
            kvVo.setValue(resDO.getTurnoverAmount());
        } else if (RecycleTendencyEnum.SUCCESS_AVG.code().equals(bo.getRecycleTendencyType())) {
            kvVo.setValue(resDO.getRecycleAveragePrice());
        }
        tendencyList.add(kvVo);
        resDO.setRecycleTendency(tendencyList);

        resDO.setSelectionMonth(DateUtil.month(queTime));

        Long monthOfferCount = 0L, monthSuccessCount = 0L;
        BigDecimal monthRecycleAmount = BigDecimal.ZERO;
        if (user.getType().equals(UserTypeEnum.OFFER_OPERATOR.code())) {
            monthOfferCount = offerOrderMapper.queryOfferCountByTimeUser(queTime, 2, user.getId(), null,
                    false);
            monthSuccessCount = recycleOrderMapper.queryRecycleSuccessCountByTimeUser(queTime, 2, user.getId(),
                    null);
            monthRecycleAmount = recycleOrderMapper.queryRecycleSuccessAmountByTimeUser(queTime, 2,
                    user.getId(), null);
        } else if (user.getType().equals(UserTypeEnum.SUM_ACCOUNT.code())) {
            monthOfferCount = offerOrderMapper.queryOfferCountByTimeUser(queTime, 2, null, user.getRecoveryId(),
                    null);
            monthSuccessCount = recycleOrderMapper.queryRecycleSuccessCountByTimeUser(queTime, 2, null,
                    user.getRecoveryId());
            monthRecycleAmount = recycleOrderMapper.queryRecycleSuccessAmountByTimeUser(queTime, 2,
                    null, user.getRecoveryId());
        }
        resDO.setMonthOfferCount(monthOfferCount);
        resDO.setMonthSuccessCount(monthSuccessCount);
        double monthSuccessRate;
        if (monthOfferCount == 0) {
            monthSuccessRate = 0D;
        } else {
            monthSuccessRate = BigDecimal.valueOf((float) monthSuccessCount / monthOfferCount.doubleValue()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
        resDO.setMonthSuccessRate(monthSuccessRate);
        resDO.setMonthRecycleAmount(monthRecycleAmount == null ? BigDecimal.ZERO : monthRecycleAmount);
        return AjaxResult.success(resDO);
    }

    @Override
    public AjaxResult queryMsgDialogueList(Long offerOrderId) {
        LambdaQueryWrapper<MsgDialogueOrder> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(MsgDialogueOrder::getOfferOrderId, offerOrderId);
        lambdaQuery.orderByAsc(MsgDialogueOrder::getSendTime);
        return AjaxResult.success(msgDialogueMapper.selectVoList(lambdaQuery));
    }

    @Override
    public AjaxResult queryRecycleOrderList(ShopRecOrderQueBo req) {
        User user = mobileBaseService.hasLogin();
        List<ShopOrderListVo> orderListVos;
        if (Objects.equals(user.getType(), UserTypeEnum.OFFER_OPERATOR.code())) {
            orderListVos = recycleOrderMapper.queryRecycleOrderList(req.getStatus(), null,
                    req.getStartAmount(), req.getEndAmount(), req.getKeyword(), null, null,
                    req.getCompanyOrShopId() == null ? null : (long) req.getCompanyOrShopId(), user.getId(), null);
        } else if (Objects.equals(user.getType(), UserTypeEnum.SUM_ACCOUNT.code())) {
            orderListVos = recycleOrderMapper.queryRecycleOrderList(req.getStatus(), req.getRecoverBusId(),
                    req.getStartAmount(), req.getEndAmount(), req.getKeyword(), null, null,
                    req.getCompanyOrShopId() == null ? null : (long) req.getCompanyOrShopId(), null, null);
        } else {
            return AjaxResult.error("没有权限");
        }

        for (ShopOrderListVo orderListVo : orderListVos) {
            InquiryOrder inquiryOrder = inquiryOrderMapper.selectById(orderListVo.getInquiryOrderId());
            List<VerifyModelOption> options = verifyModelOptionMapper.selectBatchIds(Arrays.asList(inquiryOrder.getVerifyModelIds().split(",")));
            orderListVo.setSpecs(options.stream().filter(s -> s.getType() == 1).map(VerifyModelOption::getName).collect(Collectors.joining(",")));
            List<FileUpload> files = uploadMapper.selectBatchIds(Arrays.asList(inquiryOrder.getFileIds().split(",")));
            List<String> fileUrls = files.stream().map(FileUpload::getUrl).collect(Collectors.toList());
            orderListVo.setFileUrls(fileUrls);
        }
        return AjaxResult.success(orderListVos);
    }

    public List<KeyValueVo> getRecycleTendencyForInquiryCount(Date startTime, User user, Integer recycleTendencyType) {
        List<KeyValueVo> resList = new ArrayList<>();
        long diffDay = DateUtil.between(startTime, new Date(), DateUnit.DAY, true);
        for (int i = 0; i < diffDay; i++) {
            KeyValueVo res = new KeyValueVo();
            DateTime queTime = DateUtil.offsetDay(startTime, i);
            res.setKey(DateUtil.formatDate(queTime).split("-")[2] + "日");

            Object val = 0;
            if (RecycleTendencyEnum.INQUIRY_COUNT.code().equals(recycleTendencyType)) {
                res.setValue(inquiryOrderMapper.queryRecycleInquiryCountByTimeBus(queTime));
            } else if (user.getType().equals(UserTypeEnum.OFFER_OPERATOR.code())) {
                if (RecycleTendencyEnum.OFFER_COUNT.code().equals(recycleTendencyType)) {
                    val = offerOrderMapper.queryOfferCountByTimeUser(queTime, 1, user.getId(), null,
                            null);
                } else if (RecycleTendencyEnum.SUCCESS_COUNT.code().equals(recycleTendencyType)) {
                    val = recycleOrderMapper.queryRecycleSuccessCountByTimeUser(queTime, 1, user.getId(),
                            null);
                } else if (RecycleTendencyEnum.SUCCESS_RATE.code().equals(recycleTendencyType)) {
                    Long successCount = recycleOrderMapper.queryRecycleSuccessCountByTimeUser(queTime, 1,
                            user.getId(), null);
                    Long offerCount = offerOrderMapper.queryOfferCountByTimeUser(queTime, 1, user.getId(), null,
                            null);
                    val = offerCount == 0 ? 0 : new BigDecimal(successCount).divide(new BigDecimal(offerCount), 2, RoundingMode.HALF_UP).doubleValue();
                } else if (RecycleTendencyEnum.SUCCESS_AMOUNT.code().equals(recycleTendencyType)) {
                    val = recycleOrderMapper.queryRecycleSuccessAmountByTimeUser(queTime, 1,
                            user.getId(), null);
                    if (val == null) val = BigDecimal.ZERO;
                } else if (RecycleTendencyEnum.SUCCESS_AVG.code().equals(recycleTendencyType)) {
                    val = recycleOrderMapper.queryRecycleAvgAmountForTime(queTime, user.getId(),
                            null);
                    if (val == null) val = BigDecimal.ZERO;
                }
            } else if (user.getType().equals(UserTypeEnum.SUM_ACCOUNT.code())) {
                if (RecycleTendencyEnum.OFFER_COUNT.code().equals(recycleTendencyType)) {
                    val = offerOrderMapper.queryOfferCountByTimeUser(queTime, 1, null, user.getRecoveryId(),
                            null);
                } else if (RecycleTendencyEnum.SUCCESS_COUNT.code().equals(recycleTendencyType)) {
                    val = recycleOrderMapper.queryRecycleSuccessCountByTimeUser(queTime, 1, null,
                            user.getRecoveryId());
                } else if (RecycleTendencyEnum.SUCCESS_RATE.code().equals(recycleTendencyType)) {
                    Long successCount = recycleOrderMapper.queryRecycleSuccessCountByTimeUser(queTime, 1,
                            null, user.getRecoveryId());
                    Long offerCount = offerOrderMapper.queryOfferCountByTimeUser(queTime, 1, null, user.getRecoveryId(),
                            null);
                    val = offerCount == 0 ? 0 : new BigDecimal(successCount).divide(new BigDecimal(offerCount), 2, RoundingMode.HALF_UP).doubleValue();
                } else if (RecycleTendencyEnum.SUCCESS_AMOUNT.code().equals(recycleTendencyType)) {
                    val = recycleOrderMapper.queryRecycleSuccessAmountByTimeUser(queTime, 1,
                            null, user.getRecoveryId());
                    if (val == null) val = BigDecimal.ZERO;
                } else if (RecycleTendencyEnum.SUCCESS_AVG.code().equals(recycleTendencyType)) {
                    val = recycleOrderMapper.queryRecycleAvgAmountForTime(queTime, null,
                            user.getRecoveryId());
                    if (val == null) val = BigDecimal.ZERO;
                }
            }
            res.setValue(val);
            resList.add(res);
        }
        return resList;
    }

    @Override
    public AjaxResult queryRecycleStatistic() {
        User user = mobileBaseService.hasLogin();
        if (!Objects.equals(user.getType(), UserTypeEnum.SUM_ACCOUNT.code())) {
            log.error("非报价商总账号，不能访问{}接口", user.getUsername());
            return AjaxResult.error("权限不足");
        }
        Date currentDate = new Date();

        RecycleWorkStatisticVo resDO = new RecycleWorkStatisticVo();
        //获取今日成交额
        resDO.setSuccessAmount(recycleOrderMapper.queryRecycleSuccessAmountByTimeUser(currentDate, 1,
                null, user.getRecoveryId()));
        //询单量
        resDO.setInquiryCount(inquiryOrderMapper.queryRecycleInquiryCountByTimeBus(currentDate));
        //报单量
        resDO.setOfferCount(offerOrderMapper.queryOfferCountByTimeUser(currentDate, 1, null, user.getRecoveryId(),
                null));
        //达成交易数量
        resDO.setSuccessCount(recycleOrderMapper.queryRecycleSuccessCountByTimeUser(currentDate, 1, null,
                user.getRecoveryId()));
        //成交率
        if (resDO.getOfferCount() == 0 || resDO.getSuccessCount() == 0) {
            resDO.setSuccessRate(0D);
        } else {
            BigDecimal a = new BigDecimal(resDO.getSuccessCount());
            BigDecimal b = new BigDecimal(resDO.getOfferCount());
            if (b.compareTo(BigDecimal.ZERO) == 0) {
                resDO.setSuccessRate(0D);
            } else {
                resDO.setSuccessRate(a.divide(b, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).doubleValue());
            }
        }
        //待报价数量
        resDO.setWaitOfferCount(inquiryOrderMapper.queryCountForOfferStatus(3, null, user.getRecoveryId()));
        //已报价数量
        resDO.setAlreadyOfferCount(inquiryOrderMapper.queryCountForOfferStatus(1, null, user.getRecoveryId()));
        //待收货数量
        resDO.setWaitReceivingCount(recycleOrderMapper.queryRecycleCountByUser(currentDate, null, user.getRecoveryId(),
                RecycleOrderStatusEnum.NO_RECEIVING.code(), null, null));
        //已退单数量
        resDO.setAlreadyRefundCount(recycleOrderMapper.queryRecycleCountByUser(currentDate, null, user.getRecoveryId(),
                RecycleOrderStatusEnum.ALREADY_REFUND.code(), null, null));
        //未成交数量
        resDO.setNoSuccessCount(offerOrderMapper.queryOfferCountByTimeUser(currentDate, 1, null,
                user.getRecoveryId(), false));
        return AjaxResult.success(resDO);
    }

    @Override
    public List<RecoverInquiryOrderListVo> queryOrderListByRecycle(Integer orderStatus, Date queTime) {
        User currentUser = mobileBaseService.hasLogin();
        List<RecoverInquiryOrderListVo> resDoList = new ArrayList<>();
        List<InquiryOrderVo> inquiryOrders;
        if (UserTypeEnum.OFFER_OPERATOR.code().equals(currentUser.getType())) {
            if (orderStatus < 3) {
                if (orderStatus == 1) orderStatus = 3;
                inquiryOrders = inquiryOrderMapper.queryListForOfferStatus(orderStatus, currentUser.getId(), null);
            } else if (orderStatus == 3 || orderStatus == 4) {
                inquiryOrders = recycleOrderMapper.queryInquiryListForRecycle(queTime, orderStatus, currentUser.getId(), null);
            } else {
                inquiryOrders = offerOrderMapper.queryNoSuccessInquiryListForRecycle(queTime, currentUser.getId(), null);
            }
        } else if (UserTypeEnum.SUM_ACCOUNT.code().equals(currentUser.getType())) {
            if (orderStatus == 0 || orderStatus == 1) {
                if (orderStatus == 1) orderStatus = 3;
                inquiryOrders = inquiryOrderMapper.queryListForOfferStatus(orderStatus, null, currentUser.getRecoveryId());
            } else if (orderStatus == 3 || orderStatus == 4) {
                inquiryOrders = recycleOrderMapper.queryInquiryListForRecycle(queTime, orderStatus, null, currentUser.getRecoveryId());
            } else {
                inquiryOrders = offerOrderMapper.queryNoSuccessInquiryListForRecycle(queTime, null, currentUser.getRecoveryId());
            }
        } else {
            return new ArrayList<>();
        }
        for (InquiryOrderVo inquiryOrder : inquiryOrders) {
            RecoverInquiryOrderListVo res = new RecoverInquiryOrderListVo();
            User user = userMapper.selectById(inquiryOrder.getUserId());
            Company company = companyMapper.selectById(user.getCompanyId());
            Company shop = companyMapper.selectById(user.getStoreId());
            res.setCompanyName(company.getName());
            res.setShopName(shop.getName());
            res.setCreateTime(inquiryOrder.getCreateTime());
            res.setModelName(inquiryOrder.getModelName());
            res.setStatusDesc(inquiryOrder.getStatusDesc());
            res.setCode(inquiryOrder.getCode());
            List<VerifyModelOption> modelOptions = verifyModelOptionMapper.selectBatchIds(Arrays.asList(inquiryOrder.getVerifyModelIds().split(",")));
            String specs = modelOptions.stream().filter(s -> s.getType() == 1).map(VerifyModelOption::getName).collect(Collectors.joining(","));
            res.setSpecs(specs);
            res.setId(inquiryOrder.getId());
            List<FileUpload> files = uploadMapper.selectBatchIds(Arrays.asList(inquiryOrder.getFileIds().split(",")));
            List<String> fileUrls = files.stream().map(FileUpload::getUrl).collect(Collectors.toList());
            res.setFileUrls(fileUrls);
            LambdaQueryWrapper<MsgDialogueOrder> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(MsgDialogueOrder::getInquiryOrderId, inquiryOrder.getId());
            wrapper.eq(MsgDialogueOrder::getIsRead, YesNoEnum.NO.code());
            wrapper.eq(MsgDialogueOrder::getReceiveUser, currentUser.getId());
            res.setMsgNoReadCount(msgDialogueMapper.selectCount(wrapper));
            resDoList.add(res);
        }
        return resDoList;
    }

    @Override
    public AjaxResult queryRecycleGoodsTrack() {
        User user = mobileBaseService.hasLogin();
        RecycleGoodsTrackVo resDO = new RecycleGoodsTrackVo();
        LambdaQueryWrapper<RecycleOrder> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(RecycleOrder::getStatus, RecycleOrderStatusEnum.NO_SEND.code());
        if (Objects.equals(user.getType(), UserTypeEnum.SHOP_OPERATOR.code())) {
            lambdaQuery.eq(RecycleOrder::getRecycleOperatorId, user.getId());
        } else if (Objects.equals(user.getType(), UserTypeEnum.SUM_ACCOUNT.code())) {
            lambdaQuery.eq(RecycleOrder::getRecycleBusId, user.getRecoveryId());
        } else {
            return AjaxResult.error("权限不足");
        }
        Long waitShipping = recycleOrderMapper.selectCount(lambdaQuery);
        resDO.setWaitShipping(waitShipping);
        Long timeoutShippingCount = 0L;
        if (Objects.equals(user.getType(), UserTypeEnum.SHOP_OPERATOR.code())) {
            timeoutShippingCount = recycleOrderMapper.queryTimeoutShippingCount(user.getId(), null);
        } else if (Objects.equals(user.getType(), UserTypeEnum.SUM_ACCOUNT.code())) {
            timeoutShippingCount = recycleOrderMapper.queryTimeoutShippingCount(null, user.getRecoveryId());
        }
        resDO.setTimeoutShipping(timeoutShippingCount);

        LambdaQueryWrapper<RecycleOrder> warehouseWrapper = Wrappers.lambdaQuery();
        warehouseWrapper.eq(RecycleOrder::getStatus, RecycleOrderStatusEnum.FINISH.code());
        if (Objects.equals(user.getType(), UserTypeEnum.SHOP_OPERATOR.code())) {
            warehouseWrapper.eq(RecycleOrder::getRecycleOperatorId, user.getId());
        } else if (Objects.equals(user.getType(), UserTypeEnum.SUM_ACCOUNT.code())) {
            warehouseWrapper.eq(RecycleOrder::getRecycleBusId, user.getRecoveryId());
        }
        Long warehouseCount = recycleOrderMapper.selectCount(warehouseWrapper);
        resDO.setWarehouse(warehouseCount);
        return AjaxResult.success(resDO);
    }

    @Override
    public AjaxResult createOrUpdateRecycleRecAddr(RecycleReceivingAddrBo bo) {
        User user = mobileBaseService.hasLogin();
//        StringBuilder addBuilder = new StringBuilder();
//        CfgArea provinceDO = areaMapper.selectById(bo.getProvinceId());
//        if (provinceDO == null) {
//            log.error("创建收货地址失败，省ID错误");
//            return AjaxResult.error("参数错误");
//        }
//        addBuilder.append(provinceDO.getName());
//        CfgArea cityDO = areaMapper.selectById(bo.getCityId());
//        if (cityDO == null) {
//            log.error("创建收货地址失败，市ID错误");
//            return AjaxResult.error("参数错误");
//        }
//        addBuilder.append(cityDO.getName());
//        CfgArea regionDO = areaMapper.selectById(bo.getRegionId());
//        if (regionDO == null) {
//            log.error("创建收货地址失败，区ID错误");
//            return AjaxResult.error("参数错误");
//        }
//        addBuilder.append(regionDO.getName());
//        addBuilder.append(bo.getDetailAddr());
//        bo.setFullAddr(addBuilder.toString());
        if (bo.getId() != null) {
            RecycleReceivingAddr receivingAddr = receivingAddrMapper.selectById(bo.getId());
            if (!Objects.equals(receivingAddr.getRecycleBusId(), user.getRecoveryId())) {
                return AjaxResult.error("参数错误");
            }
            BeanUtils.copyProperties(bo, receivingAddr);
            receivingAddrMapper.updateById(receivingAddr);
        } else {
            LambdaQueryWrapper<RecycleReceivingAddr> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(RecycleReceivingAddr::getRecycleBusId, user.getRecoveryId());
            Long count = receivingAddrMapper.selectCount(wrapper);
            if (count > 0) {
                return AjaxResult.error("地址已存在");
            }
            RecycleReceivingAddr receivingAddr = new RecycleReceivingAddr();
            BeanUtils.copyProperties(bo, receivingAddr);
            receivingAddr.setRecycleBusId(user.getRecoveryId());
            receivingAddrMapper.insert(receivingAddr);
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult delRecycleRecAddr(Integer id) {
        int count = receivingAddrMapper.deleteById(id);
        return count > 0 ? AjaxResult.success() : AjaxResult.error("删除失败");
    }

    @Override
    public AjaxResult queryRecycleRecAddrList(String keyword) {
        User user = mobileBaseService.hasLogin();
        LambdaQueryWrapper<RecycleReceivingAddr> addrWrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotEmpty(keyword)) {
            addrWrapper.like(RecycleReceivingAddr::getFullAddr, "%" + keyword + "%");
        }
        addrWrapper.eq(RecycleReceivingAddr::getRecycleBusId, user.getRecoveryId());
        List<RecycleReceivingAddrVo> addrVos = receivingAddrMapper.selectVoList(addrWrapper);
        return AjaxResult.success(addrVos);
    }

    @Override
    public AjaxResult bindCompany(Integer companyId) {
        User user = mobileBaseService.hasLogin();
        Company company = companyMapper.selectById(companyId);
        if (company == null) {
            return AjaxResult.error("公司不存在");
        }
        LambdaQueryWrapper<CompanyRecoverInfo> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CompanyRecoverInfo::getCompanyId, companyId);
        wrapper.eq(CompanyRecoverInfo::getRecoveryId, user.getRecoveryId());
        Long count = companyRecoverInfoMapper.selectCount(wrapper);
        if (count > 0) {
            return AjaxResult.success();
        }
        CompanyRecoverInfo companyRecoverDO = new CompanyRecoverInfo();
        companyRecoverDO.setCompanyId((long) companyId);
        companyRecoverDO.setRecoveryId(user.getRecoveryId());
        companyRecoverInfoMapper.insert(companyRecoverDO);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult delBindCompany(Integer id) {
        int count = companyRecoverInfoMapper.deleteById(id);
        return count > 0 ? AjaxResult.success() : AjaxResult.error("删除失败");
    }

    @Override
    public AjaxResult queryBindCompanyList(String companyName) {
        User user = mobileBaseService.hasLogin();
        return AjaxResult.success(companyRecoverInfoMapper.queryBindCompanyList(companyName, user.getRecoveryId()));
    }

}
